package com.bzgwl.mybatis_plus.security;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bzgwl.mybatis_plus.sys.entity.Role;
import com.bzgwl.mybatis_plus.sys.entity.User;
import com.bzgwl.mybatis_plus.sys.mapper.RoleMapper;
import com.bzgwl.mybatis_plus.sys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Professor_Kong
 * date: 2018/3/22
 */
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
@Service
@SuppressWarnings("all") //抑制所以黄线警告
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        try {

            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("username",userName);
            List<User> sysUserList = userMapper.selectList(wrapper);

            if(sysUserList == null || sysUserList.size() <=0){
                throw new UsernameNotFoundException("UserName " + userName + " not found");
            }
            User user = sysUserList.get(0);
            // SecurityUser实现UserDetails并将SUser的Email映射为username
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

            List<Role> roles=roleMapper.getRoleById(user.getId());
            if(roles == null || roles.size() <=0){
                return  null;
            }
            for (Role ur : roles) {
                String name = ur.getName();
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(name);
                authorities.add(grantedAuthority);
            }
            //注意这里返回的是 security 里面的user
            return new org.springframework.security.core.userdetails.User(
                    user.getUsername(),
                    user.getPassword(),
                    authorities);
        }catch ( Exception e){
            e.printStackTrace();
            return null;
        }

    }

}